package service

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"time"

	"temp/auth"
	"temp/constant"
	"temp/model"
	"temp/util"

	"github.com/redis/go-redis/v9"
	"gorm.io/gorm"
)

type UserService struct {
	db    *gorm.DB
	cache *redis.Client
}

func (u *UserService) Login(ctx context.Context, username, password string) (string, error) {
	// 获取用户信息
	var user model.User
	err := u.db.WithContext(ctx).Where("name = ?", username).First(&user).Error
	if err != nil {
		return "", err
	}
	// 验证密码
	if !auth.ValidatePassword(password, user.PassWord) {
		return "", errors.New("密码错误")
	}

	// 生成token
	token, err := auth.GenerateToken(user.ID, user.Name)
	if err != nil {
		return "", err
	}
	// 将token存储到redis中
	u.cache.Set(ctx, fmt.Sprintf(constant.UserTokenKey, user.ID), token, time.Duration(constant.Token_Expired))

	// 将用户信息存储到redis中，便于后续获取
	userInfo, _ := json.Marshal(user)
	u.cache.Set(ctx, fmt.Sprintf("user_info:%d", user.ID), userInfo, time.Duration(constant.Token_Expired))

	ctx = context.WithValue(ctx, model.AuthUserKey, user)
	return token, nil
}

func (u *UserService) getUser(user *model.User) *model.User {
	var result model.User
	err := u.db.Where(user).First(&result).Error
	if err != nil {
		return nil
	}
	return &result
}

func (u *UserService) Register(ctx context.Context, username, password string) error {
	user := model.User{
		Name:     username,
		PassWord: auth.HashPassword(password),
	}
	var exists int64
	if err := u.db.WithContext(ctx).Model(&model.User{}).Where("name = ?", username).Count(&exists).Error; err != nil {
		return err
	}
	if exists > 0 {
		return errors.New("用户已存在")
	}

	return u.db.WithContext(ctx).Create(&user).Error
}

func (u *UserService) getByID(id int64) *model.User {
	var user model.User
	err := u.db.Where("id = ?", id).First(&user).Error
	if err != nil {
		return nil
	}
	return &user
}

func (u *UserService) Update(ctx context.Context, user *model.User) error {
	return u.db.WithContext(ctx).Save(user).Error
}
func (u *UserService) Delete(ctx context.Context, id int64) error {
	return u.db.WithContext(ctx).Delete(&model.User{}, id).Error
}
func (u *UserService) List() []*model.User {
	var users []*model.User
	u.db.Find(&users)
	return users
}

func (u *UserService) page(req *util.PageRequest) (*util.PageResponse, error) {
	// 获取总记录数
	var total int64
	if err := u.db.Model(&model.User{}).Where(req.Modal).Count(&total).Error; err != nil {
		return nil, err
	}

	// 查询列表数据
	var users []model.User
	if err := u.db.Offset(int(req.GetOffset())).Limit(int(req.GetLimit())).Find(&users).Error; err != nil {
		return nil, err
	}

	// 构建分页响应
	return util.BuildPageResponse(req, users, total), nil

}

func (u *UserService) CreateUser(ctx context.Context, user model.User) error {

	if result := u.db.Model(&model.User{}).WithContext(ctx).Where("username = ?", user.Name); result.Error != nil {
		if result.RowsAffected != 0 {
			return errors.New("重复的用户名称")
		}
		return result.Error
	}
	if result := u.db.WithContext(ctx).Where("phone = ?", user.Phone); result.Error != nil {
		if result.RowsAffected != 0 {
			return errors.New("重复的手机号名称")
		}
		return result.Error
	}
	user.Phone = auth.HashPassword(user.PassWord)
	return u.db.WithContext(ctx).Create(&user).Error

}

func (u *UserService) Roles(ctx context.Context, user string, roles []string) error {
	var roleModals []model.UserRoles
	for _, v := range roles {
		roleModals = append(roleModals, model.UserRoles{
			UserId: util.StringToInt64Unsafe(user),
			RoleId: util.StringToInt64Unsafe(v),
		})
	}
	return u.db.WithContext(ctx).Model(&model.Role{}).Create(roleModals).Error
}
func NewUserService(db *gorm.DB, cache *redis.Client) *UserService {
	return &UserService{
		db:    db,
		cache: cache,
	}
}
